<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{height: height+'px','overflow-y': hidden}"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="onChange"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, onBeforeMount } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 接收父组件数据
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  }
})
// 编辑器大小控制
let height=ref()
onBeforeMount(()=>{
  window.innerHeight>500?height.value=window.innerHeight-414:height.value=500
})
window.onresize=()=>{
  if(window.innerHeight>500){
    height.value=window.innerHeight-414
  }
}

const mode = ref('default');
const editorRef = shallowRef()
// toolbar设置
const toolbarConfig = {}
// HTML内容
const editorConfig = {
  placeholder: '请输入内容...', MENU_CONF: {
    uploadImage: {
      maxFileSize: 3 * 1024 * 1024,
      server: "/api/file/uploadImage4WangEditor",
      customInsert (res, insertFn) {
        insertFn(res.data.url, "", "");
      }
    }
  }
}

const emit = defineEmits()

// 编辑器创建时记录editor实例
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 内容改变时触发
const onChange = (editor) => {
  emit("update:modelValue", editor.getHtml());
}

// 组件销毁时销毁编辑器 
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style lang="scss" scoped>
</style>